/**
 * 
 */
package com.et114.core.action;

// Created by MyEclipse Struts
// XSL source (default):
// platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_3.8.3/xslt/JavaClass.xsl

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import net.sf.ehcache.CacheException;

import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

//import com.et114.components.acegi.cache.AcegiCacheManager;
import com.et114.components.acegi.Constants;
import com.et114.core.common.AppContext;
import com.et114.core.common.CONST;
import com.et114.core.common.Error;
import com.et114.core.control.TokenMapClient;
import com.et114.core.exception.CheckException;
import com.et114.core.exception.ModuleException;
import com.et114.core.resources.FrameworkMessageManager;
import com.et114.core.utility.TokenMapUtils;
import com.et114.modules.org.utility.SessionUserInfo;


/**
 * @author guanhw
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
/**
 * 
 * XDoclet definition:
 * 
 */
public class BaseAction extends Action {

	protected Log logger = LogFactory.getLog( this.getClass() );

	
	// --------------------------------------------------------- Instance
	// Variables

	// --------------------------------------------------------- Methods

	/**
	 * Method execute
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public final ActionForward execute( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) {
		//令牌检查
		try {
			TokenMapClient client = ( TokenMapClient ) this.getBean (  "tokenMapClient" );
			boolean isTokenValid = false;
			if ( TokenMapUtils.isExistToken ( request , client , CONST.SAVE_TOKEN ) ) {
				saveToken ( request );
				
			}// 判断提交的action是否在保存token表中注册过，如果是，则保存token值，并将isSaved设为true
			
			if ( TokenMapUtils.isExistToken ( request , client , CONST.CHECK_TOKEN ) ) {
				isTokenValid = isTokenValid ( request );
				if ( !isTokenValid ) {
					Error error = new Error();
					error.setGoBack ( false ) ; 
					error.setErrorTitle ( FrameworkMessageManager.get ( ).getMessage ( "submit.resubmit" , request.getLocale ( ) ) ) ;
					request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
					return mapping.findForward( "glerror" ) ;
				}			
			}
			if ( isTokenValid )	resetToken ( request );
			
		//结束令牌检查
			return toExecute( mapping , form , request , response  );
		}
		catch ( Throwable e ) {
			String goBackUrl = null;
			String em = null ; 
			if ( e instanceof CacheException ) {
				CacheException cacheEx = ( CacheException ) e;
				logger.error ( "Base CacheException::" + e.getMessage ( ) , cacheEx );
			} else if ( e instanceof CheckException ) {
				CheckException ce = ( CheckException ) e;
				goBackUrl = ce.getGoBackUrl ( );
				em = ce.getMessage ( ) ; 
				logger.error ( "CheckException::" + e.getMessage ( ) , ce );
			} else if ( e instanceof ModuleException ) { 
				ModuleException mex = ( ModuleException )  e ; 
				String bundle = mex.getBundle ( ) ; 
				if ( bundle == null  )  bundle = Globals.MESSAGES_KEY ;
				Object [ ] object = ( ( ModuleException ) e ).getActionMessage ( ).getValues ( );
				String expkey = ( ( ModuleException ) e ).getActionMessage ( ).getKey ( );
				em = getResources ( request , bundle ).getMessage ( expkey , object ) ; 
				goBackUrl = mex.getGoBackUrl ( ) ; 
				logger.error( "ModuleException::" + em , mex ) ;
			}
			else if ( e instanceof Exception ) {
				Exception ee = ( Exception ) e;
				if ( !Constants.AUTH_ACCESSDENIED.equals ( ee.getMessage ( ) ) 
						&& ( ee.getMessage ( ) != null 
								&& !ee.getMessage ( ).startsWith ( Constants.SYS_EXP_K ) ) )
					logger.error( "Exception::" + ee.getMessage ( ) , ee ) ;
				else {
					em = ee.getMessage ( ) ;
					if ( em != null && em.startsWith ( Constants.AUTH_ACCESSDENIED ) )
						em = em.replaceAll ( Constants.AUTH_ACCESSDENIED , "" ) ; 
					if ( em != null && em.startsWith ( Constants.SYS_EXP_K ) ) 
						em = em.replaceAll ( Constants.SYS_EXP_K , "" ) ; 
					logger.error( "ExceptionT::" + ee.getMessage ( ) , ee ) ;
				} 
			}
			else logger.error( "Error::" + e.getMessage ( ) , e ) ;
//error info;
			Error error = new Error();
			error.setErrorTitle ( em ) ;
			//error.setErrorInfo ( e.getStackTrace ( )  ) ;
			if ( goBackUrl != null && !"".equals ( goBackUrl.trim ( ) ) ) error.setGoBackUrl ( goBackUrl ) ;
			request.setAttribute (  CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;				
			return mapping.findForward( "glerror" ) ;
		}
	}
   
	
	/**
	 * Method execute
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	protected ActionForward toExecute( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		return null;
	}
	
	/**
	 * 
	 * @param beanname
	 * @return
	 */
	protected Object getBean( String beanname ) throws CheckException {
		return AppContext.getBean( beanname ) ;	
	}

	/**
	 * 
	 * @param request
	 * @return
	 */
	public SessionUserInfo getCurrentUser( HttpServletRequest request ) {
		HttpSession session = request.getSession ( );
		return  ( SessionUserInfo ) session .getAttribute ( Constants.SESSION_CURRENT_USER_KEY );
	}

}